/*  File Name	: Monitor.cpp
 *  Author		: Javie Pong
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2011-9-1
 *  Description:
 */

#ifndef MONITOR_CPP_
#define MONITOR_CPP_
#include "Monitor.h"


MonitorEx::MonitorEx()
{
	this->block_size_ = 1024;
	this->msgblock_pool_ =NULL;
	this->reactor_ = NULL;
	this->pool_name_ = "MonitorEx";
	this->thread_list_.clear();
	//this->unique_id_ = 1;
}

MonitorEx::~MonitorEx()
{
	DELETE(this->msgblock_pool_);
	if(this->thread_list_.size()>0)
	{
		for(MonitorEx::ThreadList::iterator iter=this->thread_list_.begin();
				iter!=this->thread_list_.end();iter++)
		{
			if(NULL!=(*iter))
			{
				DELETE(*iter);
			}
		}
	}
}

int MonitorEx::init(int list_size,int block_size,std::string pool_name)
{
	this->request_list_ = new DuplexList(list_size);
	if(NULL==this->request_list_)
	{
		return -1;
	}

	this->respond_list_ = new DuplexList(list_size);
	if(NULL==this->respond_list_)
	{
		return -1;
	}

	this->msg_pool_info(block_size,pool_name);
	return 0;
}
int MonitorEx::start(void)
{
	for(MonitorEx::ThreadList::iterator iter=this->thread_list_.begin();
			iter!=this->thread_list_.end();iter++)
	{
		(*iter)->activate();
	}
	return 0;
}
int MonitorEx::stop(void)
{
	return 0;
}

int MonitorEx::request_mb_pop(MessageBlock *&mb)
{
	return this->request_list_->get_obj((void*&)mb);
}

int MonitorEx::request_mb_push(MessageBlock *mb)
{
	return this->request_list_->put_obj(mb);
}

int MonitorEx::respond_mb_pop(MessageBlock *&mb)
{
	return this->respond_list_->get_obj((void*&)mb);
}

int MonitorEx::respond_mb_push(MessageBlock *mb)
{
	return this->respond_list_->put_obj(mb);
}

Reactor *MonitorEx::reactor(Reactor *reactor)
{
	if(NULL!=reactor)
	{
		this->reactor_ = reactor;
	}
	return this->reactor_;
}

void MonitorEx::msg_pool_info(int block_size,std::string pool_name)
{
	this->block_size_ =block_size;
	this->pool_name_= pool_name;
}

MsgBlockPool *MonitorEx::msg_pool(void)
{
	if(NULL==this->msgblock_pool_)
	{
		this->msgblock_pool_ = new MsgBlockPool(block_size_,pool_name_);
	}
	return this->msgblock_pool_;
}


DuplexList *MonitorEx::request_list(void) const
{
	return this->request_list_;
}

DuplexList *MonitorEx::respond_list(void) const
{
	return this->respond_list_;
}

//int MonitorEx::get_unique_id(void)
//{
//	return this->unique_id_++;
//}

const int MonitorEx::monitor_id(void)
{
	return 0;
}

void MonitorEx::wait_thread_exit(void)
{
	if(this->thread_list_.size()>0)
	{
		for(MonitorEx::ThreadList::iterator iter=this->thread_list_.begin();
				iter!=this->thread_list_.end();iter++)
		{
			if(NULL!=(*iter))
			{
				(*iter)->wait();
				LOG((DEBUG_LOG,"MonitorEx::wait_thread_exit [%l]",(*iter)->thread_id()));
			}
		}
	}
}
#endif //MONITOR_CPP_
